<template>
  <div class="app-container">
    <!--对象搜索树型列表-->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="任务名称" prop="job">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <y-select
          v-model="queryParams.status"
          placeholder="请选择执行状态"
          :options="sys_enable_disable"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--对象操作-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Back" @click="handleBack"
          >返回</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Suitcase"
          @click="handleJobPlugins"
          >插件</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['oms:job:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oms:job:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="CaretRight"
          :disabled="single"
          @click="handleStart"
          v-hasPermi="['oms:job:start']"
          >执行</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="SwitchButton"
          :disabled="single"
          @click="handleStop"
          v-hasPermi="['oms:job:stop']"
          >停止</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['oms:job:delete']"
          >删除</el-button
        >
      </el-col>

      <y-right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      />
    </el-row>

    <!--对象列表-->
    <el-table
      ref="tableRef"
      v-loading="loading"
      row-key="id"
      :data="jobList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        reserve-selection
      />
      <el-table-column label="序号" width="100" align="center" type="index">
        <template #default="scope">
          {{ scope.$index + (queryParams.page - 1) * queryParams.limit + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="任务编号"
        align="center"
        width="300"
        prop="id"
        v-if="columns[0].visible"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="任务名称"
        align="center"
        min-width="300"
        prop="name"
        :show-overflow-tooltip="true"
        v-if="columns[1].visible"
        sortable
      >
      </el-table-column>
      <el-table-column
        label="执行表达式"
        align="center"
        prop="cron"
        width="180"
        v-if="columns[2].visible"
        sortable
      >
      </el-table-column>
      <el-table-column
        label="任务状态"
        width="120"
        align="center"
        prop="status"
        v-if="columns[3].visible"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="tms_job_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="create_time"
        width="180"
        v-if="columns[4].visible"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" align="center" width="200">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['oms:job:edit']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="执行" placement="top">
            <el-button
              :disabled="scope.row.status == '1' || scope.row.status == '2'"
              link
              type="primary"
              icon="CaretRight"
              @click="handleStart(scope.row)"
              v-hasPermi="['oms:job:start']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="停止" placement="top">
            <el-button
              link
              type="primary"
              icon="SwitchButton"
              @click="handleStop(scope.row)"
              v-hasPermi="['oms:job:stop']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="日志" placement="top">
            <el-button
              link
              type="primary"
              icon="ChatDotSquare"
              @click="handleLog(scope.row)"
              v-hasPermi="['oms:job:log']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['oms:job:delete']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--列表分页-->
    <y-pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <au-job
      :id="id"
      v-model="open"
      :title="title"
      :operate="operate"
      :getMethod="getHawkeyeJob"
      :addMethod="addHawkeyeJob"
      :updateMethod="updateHawkeyeJob"
      @submited="submited"
      @close="open = false"
    >
    </au-job>

    <!-- 任务插件 -->
    <job-plugin
      v-model="openJobPlugin"
      :job="id"
      title="任务插件"
      @close="openJobPlugin = false"
    />

    <!-- 用例日志详情展示 -->
    <el-dialog
      title="执行日志"
      v-model="openLog"
      width="1000px"
      @close="openLog = false"
      append-to-body
    >
      <el-form :model="form" label-width="100px">
        <el-input
          :rows="15"
          readonly="readonly"
          prop="detail"
          label-width="100px"
          v-model="form.detail"
          type="textarea"
        />
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="HawkeyeJob">
import useUserStore from "@/store/modules/user";
import {
  getHawkeyeJob,
  addHawkeyeJob,
  updateHawkeyeJob,
  startHawkeyeJob,
  stopHawkeyeJob,
  listHawkeyeJob,
  delHawkeyeJob,
  changeHawkeyeJobStatus,
} from "@/api/oms/hawkeye/job";
import AuJob from "./components/AuJob";
import JobPlugin from "./components/JobPlugin";

const route = useRoute();
const { proxy } = getCurrentInstance();
const { sys_enable_disable,tms_job_status } = proxy.useDict("sys_enable_disable","tms_job_status");

const id = ref(null);
const ids = ref([]);
const idsn = ref([]);
const open = ref(false);
const openLog = ref(false);
const title = ref("");
const total = ref(0);
const loading = ref(true);
const showSearch = ref(false);
const single = ref(true);
const multiple = ref(true);
const dateRange = ref([]);
const operate = ref("add");
const jobList = ref([]);
const openJobPlugin = ref(false);

// 列显隐信息
const columns = ref([
  { key: 0, label: `任务编号`, visible: false },
  { key: 1, label: `任务名称`, visible: true },
  { key: 2, label: `执行表达式`, visible: true },
  { key: 3, label: `任务状态`, visible: true },
  { key: 4, label: `创建时间`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    job: route.query.job,
    status: undefined,
    page: 1,
    limit: 10,
  },
});

const { queryParams, form } = toRefs(data);

/** 查询执行日志列表 */
function getList() {
  loading.value = true;
  listHawkeyeJob(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      jobList.value = response.data;
      total.value = response.total;
      loading.value = false;
    }
  );
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  idsn.value = selection.map((item) => item.name);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 返回操作 */
function handleBack() {
  proxy.$router.back();
}

/** 新增按钮操作 */
function handleAdd() {
  operate.value = "add";
  open.value = true;
  title.value = "添加任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  id.value = row.id || ids.value;
  operate.value = "update";
  open.value = true;
  title.value = "修改任务";
}

/** 任务插件列表查询 */
function handleJobPlugins() {
  openJobPlugin.value = true;
  title.value = "任务插件";
}

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.name + '"任务吗?')
    .then(function () {
      return changeHawkeyeJobStatus(row);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}

/** 开始执行*/
function handleStart(row) {
  ids.value = row.id ? [row.id] : ids.value;
  idsn.value = row.name || idsn.value;
  proxy.$modal
    .confirm('确认要开始执行"' + idsn.value + '"任务吗?')
    .then(function () {
      useUserStore()
        .getInfo()
        .then((res) => {
          startHawkeyeJob(ids.value).then(() => {
            getList();
            proxy.$modal.msgSuccess("任务开始执行");
          });
        });
    });
}

/** 停止执行*/
function handleStop(row) {
  ids.value = row.id ? [row.id] : ids.value;
  idsn.value = row.name || idsn.value;
  proxy.$modal
    .confirm('确认要停止执行"' + idsn.value + '"任务吗?')
    .then(function () {
      stopHawkeyeJob(ids.value).then((res) => {
        getList();
        proxy.$modal.msgSuccess(res.msg);
      });
    });
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    if (row.id) {
      await proxy.$modal.confirm(`确认是否删除 "${row.name}" ？`);
    } else {
      await proxy.$modal.confirm("确认是否删除所有已勾选信息？");
    }
    ids.value = row.id ? [row.id] : ids.value;
    await delHawkeyeJob(ids.value);
    proxy.$modal.msgSuccess("删除成功");
    proxy.$refs.tableRef.clearSelection();
    getList();
  } catch (error) {
    console.error(error);
  }
}

/** 详细日志按钮操作 */
function handleLog(row) {
  openLog.value = true;
  form.value = row;
}

/** 添加/修改对象后触发事件 */
function submited() {
  getList();
}

onMounted(() => {
  getList();
});
</script>
